package com.amsp.oa.oademo.controller;

import com.amsp.oa.oademo.entity.JobResponsibility;
import com.amsp.oa.oademo.service.JobResponsibilityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/job-responsibility")
@Api(tags = "岗位职责目标责任书管理")
public class JobResponsibilityController {

    @Autowired
    private JobResponsibilityService jobResponsibilityService;

    @GetMapping("/list")
    @ApiOperation("获取岗位职责目标责任书列表")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String department) {

        List<JobResponsibility> list = jobResponsibilityService.getList(page, limit, name, department);
        long total = jobResponsibilityService.getTotal(name, department);

        Map<String, Object> response = new HashMap<>();
        response.put("data", list);
        response.put("total", total);

        return ResponseEntity.ok(response);
    }

    @PostMapping("/save")
    @ApiOperation("创建或更新岗位职责目标责任书")
    public ResponseEntity<JobResponsibility> saveOrUpdate(@RequestBody JobResponsibility jobResponsibility) {
        JobResponsibility result;
        if (jobResponsibility.getId() != null) {
            // 有 ID，执行更新操作
            result = jobResponsibilityService.update(jobResponsibility.getId(), jobResponsibility);
        } else {
            // 无 ID，执行新增操作
            result = jobResponsibilityService.create(jobResponsibility);
        }
        return ResponseEntity.ok(result);
    }

    @PutMapping("/update/{id}")
    @ApiOperation("更新岗位职责目标责任书")
    public ResponseEntity<JobResponsibility> update(@PathVariable Long id,
            @RequestBody JobResponsibility jobResponsibility) {
        JobResponsibility updated = jobResponsibilityService.update(id, jobResponsibility);
        return ResponseEntity.ok(updated);
    }

    @GetMapping("/view/{id}")
    @ApiOperation("获取岗位职责目标责任书详情")
    public ResponseEntity<JobResponsibility> getById(@PathVariable Long id) {
        JobResponsibility jobResponsibility = jobResponsibilityService.getById(id);
        return ResponseEntity.ok(jobResponsibility);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除岗位职责目标责任书")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        jobResponsibilityService.delete(id);
        return ResponseEntity.ok().build();
    }
}